package com.hanxiaozhang.http.dispatcher;

import com.hanxiaozhang.http.BaseController;
import com.hanxiaozhang.http.config.Context;

import com.hanxiaozhang.http.constant.ContextConstant;
import io.netty.handler.codec.http.HttpResponseStatus;

/**
 * 功能描述: <br>
 * 〈Http请求分发器〉
 *
 * @Author:hanxiaozhang
 * @Date: 2022/1/7
 */
public class HttpRequestDispatcher implements Dispatcher {

    private HandlerMapper mapper;

    public void put(String key, BaseController processor) {
        mapper.registerHandler(key, processor);
    }

    public void setMapper(HandlerMapper mapper) {
        this.mapper = mapper;
    }


    @Override
    public Object dispatch(Context context) {
        ResponseModel model = new ResponseModel();
        model.setStatus(HttpResponseStatus.NOT_FOUND);
        model.setContent("404");

        if (null != context) {
            String key = context.getString(ContextConstant.CONTROLLER_KEY, "");
            BaseController controller = mapper.get(key);
            if (null != controller) {
                Object res = controller.process(context);
                model.setStatus(HttpResponseStatus.OK);
                model.setContent(res);
            }
        }
        return model;
    }
}
